home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / urlparse.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  14KB  |  505 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Parse (absolute and relative) URLs.
  5.  
  6. urlparse module is based upon the following RFC specifications.
  7.  
  8. RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
  9. and L.  Masinter, January 2005.
  10.  
  11. RFC 2732 : "Format for Literal IPv6 Addresses in URL\'s by R.Hinden, B.Carpenter
  12. and L.Masinter, December 1999.
  13.  
  14. RFC 2396:  "Uniform Resource Identifiers (URI)": Generic Syntax by T.
  15. Berners-Lee, R. Fielding, and L. Masinter, August 1998.
  16.  
  17. RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998.
  18.  
  19. RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
  20. 1995.
  21.  
  22. RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
  23. McCahill, December 1994
  24.  
  25. RFC 3986 is considered the current standard and any future changes to
  26. urlparse module should conform with it.  The urlparse module is
  27. currently not entirely compliant with this RFC due to defacto
  28. scenarios for parsing, and for backward compatibility purposes, some
  29. parsing quirks from older RFCs are retained. The testcases in
  30. test_urlparse.py provides a good indicator of parsing behavior.
  31.  
  32. '''
  33. import re
  34. __all__ = [
  35.     'urlparse',
  36.     'urlunparse',
  37.     'urljoin',
  38.     'urldefrag',
  39.     'urlsplit',
  40.     'urlunsplit',
  41.     'parse_qs',
  42.     'parse_qsl']
  43. uses_relative = [
  44.     'ftp',
  45.     'http',
  46.     'gopher',
  47.     'nntp',
  48.     'imap',
  49.     'wais',
  50.     'file',
  51.     'https',
  52.     'shttp',
  53.     'mms',
  54.     'prospero',
  55.     'rtsp',
  56.     'rtspu',
  57.     '',
  58.     'sftp',
  59.     'svn',
  60.     'svn+ssh']
  61. uses_netloc = [
  62.     'ftp',
  63.     'http',
  64.     'gopher',
  65.     'nntp',
  66.     'telnet',
  67.     'imap',
  68.     'wais',
  69.     'file',
  70.     'mms',
  71.     'https',
  72.     'shttp',
  73.     'snews',
  74.     'prospero',
  75.     'rtsp',
  76.     'rtspu',
  77.     'rsync',
  78.     '',
  79.     'svn',
  80.     'svn+ssh',
  81.     'sftp',
  82.     'nfs',
  83.     'git',
  84.     'git+ssh']
  85. uses_params = [
  86.     'ftp',
  87.     'hdl',
  88.     'prospero',
  89.     'http',
  90.     'imap',
  91.     'https',
  92.     'shttp',
  93.     'rtsp',
  94.     'rtspu',
  95.     'sip',
  96.     'sips',
  97.     'mms',
  98.     '',
  99.     'sftp',
  100.     'tel']
  101. non_hierarchical = [
  102.     'gopher',
  103.     'hdl',
  104.     'mailto',
  105.     'news',
  106.     'telnet',
  107.     'wais',
  108.     'imap',
  109.     'snews',
  110.     'sip',
  111.     'sips']
  112. uses_query = [
  113.     'http',
  114.     'wais',
  115.     'imap',
  116.     'https',
  117.     'shttp',
  118.     'mms',
  119.     'gopher',
  120.     'rtsp',
  121.     'rtspu',
  122.     'sip',
  123.     'sips',
  124.     '']
  125. uses_fragment = [
  126.     'ftp',
  127.     'hdl',
  128.     'http',
  129.     'gopher',
  130.     'news',
  131.     'nntp',
  132.     'wais',
  133.     'https',
  134.     'shttp',
  135.     'snews',
  136.     'file',
  137.     'prospero',
  138.     '']
  139. scheme_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.'
  140. MAX_CACHE_SIZE = 20
  141. _parse_cache = { }
  142.  
  143. def clear_cache():
  144.     '''Clear the parse cache.'''
  145.     _parse_cache.clear()
  146.  
  147.  
  148. class ResultMixin(object):
  149.     '''Shared methods for the parsed result objects.'''
  150.     
  151.     def username(self):
  152.         netloc = self.netloc
  153.         if '@' in netloc:
  154.             userinfo = netloc.rsplit('@', 1)[0]
  155.             if ':' in userinfo:
  156.                 userinfo = userinfo.split(':', 1)[0]
  157.             return userinfo
  158.  
  159.     username = property(username)
  160.     
  161.     def password(self):
  162.         netloc = self.netloc
  163.         if '@' in netloc:
  164.             userinfo = netloc.rsplit('@', 1)[0]
  165.             if ':' in userinfo:
  166.                 return userinfo.split(':', 1)[1]
  167.  
  168.     password = property(password)
  169.     
  170.     def hostname(self):
  171.         netloc = self.netloc.split('@')[-1]
  172.         if '[' in netloc and ']' in netloc:
  173.             return netloc.split(']')[0][1:].lower()
  174.         if None in netloc:
  175.             return netloc.split(':')[0].lower()
  176.         if None == '':
  177.             return None
  178.         return None.lower()
  179.  
  180.     hostname = property(hostname)
  181.     
  182.     def port(self):
  183.         netloc = self.netloc.split('@')[-1].split(']')[-1]
  184.         if ':' in netloc:
  185.             port = netloc.split(':')[1]
  186.             port = int(port, 10)
  187.             if port <= port:
  188.                 pass
  189.             elif port <= 65535:
  190.                 return port
  191.  
  192.     port = property(port)
  193.  
  194. from collections import namedtuple
  195.  
  196. class SplitResult(namedtuple('SplitResult', 'scheme netloc path query fragment'), ResultMixin):
  197.     __slots__ = ()
  198.     
  199.     def geturl(self):
  200.         return urlunsplit(self)
  201.  
  202.  
  203.  
  204. class ParseResult(namedtuple('ParseResult', 'scheme netloc path params query fragment'), ResultMixin):
  205.     __slots__ = ()
  206.     
  207.     def geturl(self):
  208.         return urlunparse(self)
  209.  
  210.  
  211.  
  212. def urlparse(url, scheme = '', allow_fragments = True):
  213.     """Parse a URL into 6 components:
  214.     <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
  215.     Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
  216.     Note that we don't break the components up in smaller bits
  217.     (e.g. netloc is a single string) and we don't expand % escapes."""
  218.     tuple = urlsplit(url, scheme, allow_fragments)
  219.     (scheme, netloc, url, query, fragment) = tuple
  220.     if scheme in uses_params and ';' in url:
  221.         (url, params) = _splitparams(url)
  222.     else:
  223.         params = ''
  224.     return ParseResult(scheme, netloc, url, params, query, fragment)
  225.  
  226.  
  227. def _splitparams(url):
  228.     if '/' in url:
  229.         i = url.find(';', url.rfind('/'))
  230.         if i < 0:
  231.             return (url, '')
  232.     i = url.find(';')
  233.     return (url[:i], url[i + 1:])
  234.  
  235.  
  236. def _splitnetloc(url, start = 0):
  237.     delim = len(url)
  238.     for c in '/?#':
  239.         wdelim = url.find(c, start)
  240.         if wdelim >= 0:
  241.             delim = min(delim, wdelim)
  242.             continue
  243.     return (url[start:delim], url[delim:])
  244.  
  245.  
  246. def urlsplit(url, scheme = '', allow_fragments = True):
  247.     """Parse a URL into 5 components:
  248.     <scheme>://<netloc>/<path>?<query>#<fragment>
  249.     Return a 5-tuple: (scheme, netloc, path, query, fragment).
  250.     Note that we don't break the components up in smaller bits
  251.     (e.g. netloc is a single string) and we don't expand % escapes."""
  252.     allow_fragments = bool(allow_fragments)
  253.     key = (url, scheme, allow_fragments, type(url), type(scheme))
  254.     cached = _parse_cache.get(key, None)
  255.     if cached:
  256.         return cached
  257.     if None(_parse_cache) >= MAX_CACHE_SIZE:
  258.         clear_cache()
  259.     netloc = query = fragment = ''
  260.     i = url.find(':')
  261.     if i > 0:
  262.         if url[:i] == 'http':
  263.             scheme = url[:i].lower()
  264.             url = url[i + 1:]
  265.             if url[:2] == '//':
  266.                 (netloc, url) = _splitnetloc(url, 2)
  267.                 if ('[' in netloc or ']' not in netloc or ']' in netloc) and '[' not in netloc:
  268.                     raise ValueError('Invalid IPv6 URL')
  269.             if allow_fragments and '#' in url:
  270.                 (url, fragment) = url.split('#', 1)
  271.             if '?' in url:
  272.                 (url, query) = url.split('?', 1)
  273.             v = SplitResult(scheme, netloc, url, query, fragment)
  274.             _parse_cache[key] = v
  275.             return v
  276.     rest = url[i + 1:]
  277.     if not rest or any((lambda .0: pass)(rest)):
  278.         scheme = url[:i].lower()
  279.         url = rest
  280.     
  281.     if url[:2] == '//':
  282.         (netloc, url) = _splitnetloc(url, 2)
  283.         if ('[' in netloc or ']' not in netloc or ']' in netloc) and '[' not in netloc:
  284.             raise ValueError('Invalid IPv6 URL')
  285.     if allow_fragments and '#' in url:
  286.         (url, fragment) = url.split('#', 1)
  287.     if '?' in url:
  288.         (url, query) = url.split('?', 1)
  289.     v = SplitResult(scheme, netloc, url, query, fragment)
  290.     _parse_cache[key] = v
  291.     return v
  292.  
  293.  
  294. def urlunparse(data):
  295.     '''Put a parsed URL back together again.  This may result in a
  296.     slightly different, but equivalent URL, if the URL that was parsed
  297.     originally had redundant delimiters, e.g. a ? with an empty query
  298.     (the draft states that these are equivalent).'''
  299.     (scheme, netloc, url, params, query, fragment) = data
  300.     if params:
  301.         url = '%s;%s' % (url, params)
  302.     return urlunsplit((scheme, netloc, url, query, fragment))
  303.  
  304.  
  305. def urlunsplit(data):
  306.     '''Combine the elements of a tuple as returned by urlsplit() into a
  307.     complete URL as a string. The data argument can be any five-item iterable.
  308.     This may result in a slightly different, but equivalent URL, if the URL that
  309.     was parsed originally had unnecessary delimiters (for example, a ? with an
  310.     empty query; the RFC states that these are equivalent).'''
  311.     (scheme, netloc, url, query, fragment) = data
  312.     if (netloc or scheme) and scheme in uses_netloc and url[:2] != '//':
  313.         url = None + '//' if url and url[:1] != '/' else '' + url
  314.     if scheme:
  315.         url = scheme + ':' + url
  316.     if query:
  317.         url = url + '?' + query
  318.     if fragment:
  319.         url = url + '#' + fragment
  320.     return url
  321.  
  322.  
  323. def urljoin(base, url, allow_fragments = True):
  324.     '''Join a base URL and a possibly relative URL to form an absolute
  325.     interpretation of the latter.'''
  326.     if not base:
  327.         return url
  328.     if not None:
  329.         return base
  330.     (bscheme, bnetloc, bpath, bparams, bquery, bfragment) = None(base, '', allow_fragments)
  331.     (scheme, netloc, path, params, query, fragment) = urlparse(url, bscheme, allow_fragments)
  332.     if scheme != bscheme or scheme not in uses_relative:
  333.         return url
  334.     if None in uses_netloc:
  335.         if netloc:
  336.             return urlunparse((scheme, netloc, path, params, query, fragment))
  337.         netloc = None
  338.     if path[:1] == '/':
  339.         return urlunparse((scheme, netloc, path, params, query, fragment))
  340.     if not None and not params:
  341.         path = bpath
  342.         params = bparams
  343.         if not query:
  344.             query = bquery
  345.         return urlunparse((scheme, netloc, path, params, query, fragment))
  346.     segments = None.split('/')[:-1] + path.split('/')
  347.     if segments[-1] == '.':
  348.         segments[-1] = ''
  349.     while '.' in segments:
  350.         segments.remove('.')
  351.     while None:
  352.         i = 1
  353.         n = len(segments) - 1
  354.         while i < n:
  355.             if segments[i] == '..' and segments[i - 1] not in ('', '..'):
  356.                 del segments[i - 1:i + 1]
  357.                 break
  358.             i = i + 1
  359.         break
  360.         continue
  361.         if segments == [
  362.             '',
  363.             '..']:
  364.             segments[-1] = ''
  365.         elif len(segments) >= 2 and segments[-1] == '..':
  366.             segments[-2:] = [
  367.                 '']
  368.         return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
  369.  
  370.  
  371. def urldefrag(url):
  372.     '''Removes any existing fragment from URL.
  373.  
  374.     Returns a tuple of the defragmented URL and the fragment.  If
  375.     the URL contained no fragments, the second element is the
  376.     empty string.
  377.     '''
  378.     if '#' in url:
  379.         (s, n, p, a, q, frag) = urlparse(url)
  380.         defrag = urlunparse((s, n, p, a, q, ''))
  381.         return (defrag, frag)
  382.     return (None, '')
  383.  
  384.  
  385. try:
  386.     unicode
  387. except NameError:
  388.     
  389.     def _is_unicode(x):
  390.         return 0
  391.  
  392.  
  393.  
  394. def _is_unicode(x):
  395.     return isinstance(x, unicode)
  396.  
  397. _hexdig = '0123456789ABCDEFabcdef'
  398. _hextochr = dict((lambda .0: pass)(_hexdig))
  399. _asciire = re.compile('([\x00-\x7f]+)')
  400.  
  401. def unquote(s):
  402.     """unquote('abc%20def') -> 'abc def'."""
  403.     if _is_unicode(s):
  404.         if '%' not in s:
  405.             return s
  406.         bits = None.split(s)
  407.         res = [
  408.             bits[0]]
  409.         append = res.append
  410.         for i in range(1, len(bits), 2):
  411.             append(unquote(str(bits[i])).decode('latin1'))
  412.             append(bits[i + 1])
  413.         
  414.         return ''.join(res)
  415.     bits = None.split('%')
  416.     if len(bits) == 1:
  417.         return s
  418.     res = [
  419.         None[0]]
  420.     append = res.append
  421.     for item in bits[1:]:
  422.         
  423.         try:
  424.             append(_hextochr[item[:2]])
  425.             append(item[2:])
  426.         continue
  427.         except KeyError:
  428.             append('%')
  429.             append(item)
  430.             continue
  431.         
  432.  
  433.     
  434.     return ''.join(res)
  435.  
  436.  
  437. def parse_qs(qs, keep_blank_values = 0, strict_parsing = 0):
  438.     '''Parse a query given as a string argument.
  439.  
  440.         Arguments:
  441.  
  442.         qs: percent-encoded query string to be parsed
  443.  
  444.         keep_blank_values: flag indicating whether blank values in
  445.             percent-encoded queries should be treated as blank strings.
  446.             A true value indicates that blanks should be retained as
  447.             blank strings.  The default false value indicates that
  448.             blank values are to be ignored and treated as if they were
  449.             not included.
  450.  
  451.         strict_parsing: flag indicating what to do with parsing errors.
  452.             If false (the default), errors are silently ignored.
  453.             If true, errors raise a ValueError exception.
  454.     '''
  455.     dict = { }
  456.     for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
  457.         if name in dict:
  458.             dict[name].append(value)
  459.             continue
  460.         dict[name] = [
  461.             value]
  462.     
  463.     return dict
  464.  
  465.  
  466. def parse_qsl(qs, keep_blank_values = 0, strict_parsing = 0):
  467.     '''Parse a query given as a string argument.
  468.  
  469.     Arguments:
  470.  
  471.     qs: percent-encoded query string to be parsed
  472.  
  473.     keep_blank_values: flag indicating whether blank values in
  474.         percent-encoded queries should be treated as blank strings.  A
  475.         true value indicates that blanks should be retained as blank
  476.         strings.  The default false value indicates that blank values
  477.         are to be ignored and treated as if they were  not included.
  478.  
  479.     strict_parsing: flag indicating what to do with parsing errors. If
  480.         false (the default), errors are silently ignored. If true,
  481.         errors raise a ValueError exception.
  482.  
  483.     Returns a list, as G-d intended.
  484.     '''
  485.     pairs = [ s2 for s1 in qs.split('&') for s2 in s1.split(';') ]
  486.     r = []
  487.     for name_value in pairs:
  488.         if not name_value and not strict_parsing:
  489.             continue
  490.         nv = name_value.split('=', 1)
  491.         if len(nv) != 2:
  492.             if strict_parsing:
  493.                 raise ValueError, 'bad query field: %r' % (name_value,)
  494.             if keep_blank_values:
  495.                 nv.append('')
  496.             
  497.         if not len(nv[1]):
  498.             if keep_blank_values:
  499.                 name = unquote(nv[0].replace('+', ' '))
  500.                 value = unquote(nv[1].replace('+', ' '))
  501.                 r.append((name, value))
  502.                 continue
  503.             return r
  504.  
  505.